package kassiopeia.plugin.crawler.moderator;

import kassiopeia.plugin.Event;
import kassiopeia.plugin.PluginException;
import kassiopeia.plugin.ProcessorPlugin;
import org.apache.log4j.Logger;

import java.util.concurrent.TimeUnit;

public class ModeratorPlugin extends ProcessorPlugin {

    private final String OUTPUT = "url-output";
    private final String TIMESTAMP_PARAMETER_NAME = "timestamp";
    private long timestamp;
    private final Logger logger = Logger.getLogger(ModeratorPlugin.class);

    /*For test purposes only*/
    public ModeratorPlugin(long timestamp) {
        this.timestamp = timestamp;
    }

    public ModeratorPlugin() {
    }

    @Override
    public void beforeTask() {
        timestamp = Long.parseLong(getContext().getParameter(TIMESTAMP_PARAMETER_NAME));
    }

    @Override
    public void process(Event event) {
        if (timestamp > 0) {
            try {
                logger.debug("Moderating event: " + event + " with timestamp[ms]: " + timestamp);
                TimeUnit.MILLISECONDS.sleep(timestamp);
                getContext().sendLocally(event, OUTPUT);
            } catch (InterruptedException ex) {
                logger.error(ex, ex);
                throw new PluginException(ex);
            }
        }
    }
}
